

package com.sjft.cloud.commons.security.rest;


import cn.hutool.http.HttpStatus;
import com.sjft.cloud.commons.core.constant.Constant;
import com.sjft.cloud.commons.core.resp.R;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;


/**
 * RestLoginSuccessHandler
 *
 * @author Jin
 */
@Slf4j
public class RestOAuth2AccessDeniedHandler extends OAuth2AccessDeniedHandler {

    @Autowired
    private  ObjectMapper objectMapper;

    /**
     * 授权拒绝处理，使用R包装
     *
     * @param request       request
     * @param response      response
     * @param authException authException
     */
    @SneakyThrows
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException authException) {
        response.setCharacterEncoding(Constant.UTF_8);
        response.setContentType(Constant.APPLICATION_JSON);
        response.setStatus(HttpStatus.HTTP_FORBIDDEN);
        PrintWriter printWriter = response.getWriter();
        printWriter.append(objectMapper.writeValueAsString(R.error("授权失败，禁止访问", "AccessDenied")));
    }


}
